<?php

namespace app\admin\controller\work;

use app\common\controller\Backend;
use app\admin\model\GradeGroup;
use app\admin\model\WorkTemplateItem;
use app\admin\model\WorkTemplate;
use think\Db;
/**
 * 浮动性工作时间模板管理管理
 *
 * @icon fa fa-circle-o
 */
class WorkTemplateTime extends Backend
{

    /**
     * WorkTemplateTime模型对象
     * @var \app\admin\model\WorkTemplateTime
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\WorkTemplateTime;
        $grade_group_arr = GradeGroup::select();
        $this->assignconfig("grade_group_arr",$grade_group_arr);
        $this->view->assign("grade_group_arr",$grade_group_arr);
        $WorkTemplate = new WorkTemplate();
        $this->view->assign("week_arr", $WorkTemplate->week_arr);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','name','start_time','end_time','create_time']);
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                Db::startTrans();
                try {
                    $validate = $this->validate($params, 'WorkTemplateTime.add');
                    if ($validate !== true) exception($validate);
                    $params['week_str'] = implode(',',$params['week_str']);
                    $grade_group_str = implode(',',$params['grade_group_arr']);
                    $params['grade_group_str'] = $grade_group_str;
                    $result = $this->model->allowField(true)->save($params);
                    if(!$result)exception('添加失败');
                    $item_arr = json_decode($params['table_data'],true);
                    foreach ($item_arr as &$v){
                        $v['work_id'] = $this->model->id;
                        $v['grade_group'] = $grade_group_str;
                    }
                    $item_result = (new WorkTemplateItem())->saveAll($item_arr);
                    if(!$item_result)exception('添加失败');
                    Db::commit();
                } catch (\Throwable $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                Db::startTrans();
                try {
                    $validate = $this->validate($params, 'WorkTemplateTime.edit');
                    if ($validate !== true) exception($validate);
                    $params['week_str'] = implode(',',$params['week_str']);
                    $grade_group_str = implode(',',$params['grade_group_arr']);
                    $params['grade_group_str'] = $grade_group_str;
                    $result = $row->allowField(true)->save($params);
                    if($result === false)exception('编辑失败');
                    $del_item = WorkTemplateItem::where('work_id',$row->id)->delete();
                    if(!$del_item)exception('编辑失败1');
                    $item_arr = json_decode($params['table_data'],true);
                    foreach ($item_arr as &$v){
                        $v['work_id'] = $row->id;
                        $v['grade_group'] = $grade_group_str;
                    }
                    $item_result = (new WorkTemplateItem())->saveAll($item_arr);
                    if(!$item_result)exception('编辑失败2');
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        $row->week_str = explode(',',$row->week_str);
        $row->grade_group_str = explode(',',$row->grade_group_str);
        $row->item_arr = collection(WorkTemplateItem::where(['work_id'=>$row->id])->select())->toArray();
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $ids = explode(',',$ids);
            try {
                $work_info = WorkTemplate::whereIn('work_time_id',$ids)->where('del_status',1)->find();
                if($work_info)exception('已被浮动性工作模版选择，请先移除浮动性工作模版');
                WorkTemplateItem::whereIn('work_id',$ids)->delete();
                $this->model->whereIn('id',$ids )->delete();
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success();
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

}
